package com.lhy.skywalking.demo.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.lhy.skywalking.demo.service.TraceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@Slf4j
public class TraceServiceImpl implements TraceService {

    @Trace(operationName = "palce_order")
    @Tag(key = "productId", value = "arg[0]")
    @Override
    public void payOrder(String order) {
        String traceId = TraceContext.traceId();
        log.info("[追踪服务：{}] 准备创建订单：{}", traceId, order);
        // 生成订单id
        String orderNo = this.generateOrderNo();
        log.info("[追踪服务：{}] 生成订单编号：{}", traceId, orderNo);
        // 获取用户信息
        String user = this.findUserBuId(1);
        // 获取商品信息
        log.info("[追踪服务：{}] 查询用户信息  ：{}", traceId, user);
        Optional<String> name = TraceContext.getCorrelation("name");
        // 创建物流信息
        log.info("[追踪服务：{}] 查询用户信息  ：{}", traceId, name);
    }

    @Trace(operationName = "order_no")
    @Tag(key="orderNo", value = "returnedObj")
    private String generateOrderNo() {
        return IdUtil.fastSimpleUUID();
    }

    @Trace(operationName = "find_user")
    @Tags({
            @Tag(key = "userId", value = "arg[0]"),
            @Tag(key = "user", value = "returnedObj")
            })
    private String findUserBuId(int userId) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", userId);
        jsonObject.put("name", "张芝山");
        return jsonObject.toJSONString();
    }
}
